package org.jeecg.common.util.valid.valid_ex;


import org.jeecg.crud.sys.model.DuplicateCheckVo;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
import java.util.function.Function;

public class DataNotExistsValidator implements ConstraintValidator<DataNotExists, String> {
    private String tableName;
    private String tableColumn;
    private Function<DuplicateCheckVo, Boolean> checkFun;



    @Override

    public void initialize(DataNotExists constraintAnnotation) {
        // 初始化校验器（通常不需要实现）
        String tableName = constraintAnnotation.tableName();
        String tableColumn = constraintAnnotation.tableColumn();
        this.tableName = tableName;
        this.tableColumn = tableColumn;
        checkFun = null;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        //为空不检查
        if (value == null || value.trim().isEmpty()) {
            return true;
        }
        return checkIfNotExistsInDatabase(value);
    }

    private boolean checkIfNotExistsInDatabase(String phoneNumber) {

        DuplicateCheckVo duplicateCheckVo = new DuplicateCheckVo();
        duplicateCheckVo.setTableName(tableName);
        duplicateCheckVo.setFieldName(tableColumn);
        duplicateCheckVo.setFieldVal(phoneNumber);
        if (Objects.isNull(checkFun)) {
            //空函数不校验
            return true;
        }
        Boolean apply = checkFun.apply(duplicateCheckVo);
        return apply;
    }
}
